var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var logger = require('morgan');

var mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/book_control');
mongoose.connection.on('connected', ()=>{
	console.log('MongoDB connected success')
})
mongoose.connection.on('error', (err)=>{
	console.log('MongoDB connected error', err)
})
mongoose.connection.on('disconnected', ()=>{
	console.log('MongoDB connected disconnected')
})

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/root/users');
var codeRouter = require('./routes/root/code');

var manegersRouter = require('./routes/root/managers');
var booksRouter = require('./routes/root/books');
var classesRouter = require('./routes/root/classes');
var intakeRouter = require('./routes/root/config/intake');
var majorRouter = require('./routes/root/config/major');
var collegeRouter = require('./routes/root/config/college');
var app = express();

app.use(session({
  name: 'sessionId',
  secret: 'zjrBook',  // 用来对session id相关的cookie进行签名
  store: new FileStore(),  // 本地存储session（文本文件，也可以选择其他store，比如redis的）
  saveUninitialized: false,  // 是否自动保存未初始化的会话，建议false
  resave: false,  // 是否每次都重新保存会话，建议false
  cookie: {
    maxAge: 60 * 1000 * 60 * 24 // 有效期，单位是毫秒
  }
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//登录拦截器
app.use((req, res, next)=>{
  if(1===1) {
  //if(req.session.isLogin) {
    next();
  } else {
    if (req.originalUrl == '/root/users/login' || req.originalUrl == '/root/users/logout' || req.originalUrl == '/root/code') {
      next();
    }else {
      res.status(401)
      res.json({
        status: '401',
        msg: '当前未登录！',
        result: ''
      })
      res.end()
    }
  }
})


app.use('/', indexRouter);
app.use('/root/code', codeRouter);
app.use('/root/users', usersRouter);
app.use('/root/managers', manegersRouter);
app.use('/root/books', booksRouter);
app.use('/root/classes', classesRouter);
app.use('/root/config/intake', intakeRouter);
app.use('/root/config/major', majorRouter);
app.use('/root/config/college', collegeRouter);
app.use('/root/upload', require('./routes/upload/index'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
